package Form;

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;

import model.entities.WeatherStation;
import model.entities.WeatherStationCollection;
import model.entities.WeatherStationReport;
import DBConnection.WeatherStationCollectionDB;
import DBConnection.WeatherStationDB;
import DBConnection.WeatherStationReportDB;

public class WeatherStationHandling {

	private WeatherStation weatherStation = null;
	private WeatherStationCollection weatherSC = null;
	private List<String> lInput = null;
	private String stationID;
	private WeatherStationReport weatherSR = null;
	private List<WeatherStationReport> lReport = null;

	public WeatherStationHandling(String stationID) {
		this.stationID = stationID;
		weatherStation = new WeatherStationDB().find(stationID);
		lReport = getAllReport();
	}

	/*
	 * Ham nay dung de doc file input.txt File input.txt la file gia lap thu
	 * thap thoi tiet
	 */
	public boolean readFileInput() {
		BufferedReader bReader = null;
		lInput = new ArrayList<String>();
		try {
			FileInputStream fileIS = new FileInputStream("input.txt");
			bReader = new BufferedReader(new InputStreamReader(fileIS));
			String input = null;
			while ((input = bReader.readLine()) != null) {
				String[] temp = input.split("\\:");
				lInput.add(temp[1]);
			}
			// Sau khi doc file thi se cap nhat vao database trang thai cua tram
			// nay
			weatherStation = new WeatherStation(stationID, "MS01", "SS01",
					Integer.parseInt(lInput.get(0)),
					lInput.get(2).equals("On") ? 1 : 0, new WeatherStationDB()
							.find(stationID).getNoChargePin(), lInput.get(1)
							.equals("Good") ? 1 : 0,
					weatherStation.getAdminRole(), 0);
			// Sau khi doc file thi se cap nhat vao database
			weatherSC = new WeatherStationCollection(stationID,
					Double.parseDouble(lInput.get(3)),
					Double.parseDouble(lInput.get(4)),
					Double.parseDouble(lInput.get(5)),
					Double.parseDouble(lInput.get(6)),
					Double.parseDouble(lInput.get(7)),
					Double.parseDouble(lInput.get(8)), Calendar.getInstance()
							.getTime().toString());
			bReader.close();
		} catch (FileNotFoundException e) {
			System.out.println("Khong tim thay file");
			e.printStackTrace();
			return false;
		} catch (IOException e) {
			System.out.println("End of File");
			e.printStackTrace();
			return false;
		} catch (NumberFormatException e) {
			System.out.println("Loi ep kieu");
			return false;
		} catch (Exception e) {
			return false;
		}
		updateDatabaseWeatherStation();
		updateDatabaseWeatherStationCollection();
		return true;
	}

	/*
	 * Ham nay dung de cap nhat doi tuong WeatherStation nay vao trong database
	 */
	public void updateDatabaseWeatherStation() {
		new WeatherStationDB().update(weatherStation);
	}

	/*
	 * Ham nay dung de cap nhat doi tuong WeatherStationCollection nay vao trong
	 * database
	 */
	public void updateDatabaseWeatherStationCollection() {
		new WeatherStationCollectionDB().add(weatherSC);

	}

	/*
	 * Ham nay de thiet lap battery cho may tram
	 */
	public void setBattery(int battery) {
		weatherStation.setBattery(battery);
		updateDatabaseWeatherStation();

	}

	/*
	 * Ham nay dung de cap nhat trang thai la tat hay mo cua may tram
	 */
	public void setStatus(int status) {
		weatherStation.setStatus(status);
		updateDatabaseWeatherStation();

	}

	/*
	 * Ham nay dung de khoi dong lai may
	 */
	public void restart() {
		weatherStation = new WeatherStationDB().find(stationID);
		updateDatabaseWeatherStation();
	}

	/*
	 * Ham nay dung de tim loi component nao bi hu tra ve list bi hu lError
	 */
	public List<String> findBug() {
		List<String> lError = new ArrayList<String>();
		// Neu la loi khong tim thay file thi return luon de size =0
		if (lInput.size() != 0) {
			try {
				Integer.parseInt(lInput.get(0));
			} catch (Exception e) {
				lError.add("Battery");
			}
			if (!(lInput.get(1).equals("Good"))) {
				lError.add("Connection");
			}
			if (!(lInput.get(2).equals("On") || lInput.get(2).equals("Off"))) {
				lError.add("Station down");
			}
			try {
				Double.parseDouble(lInput.get(3));
			} catch (Exception e) {
				lError.add("Wind Speed");
			}
			try {
				Double.parseDouble(lInput.get(4));
			} catch (Exception e) {
				lError.add("Air Blast");
			}
			try {
				Double.parseDouble(lInput.get(5));
			} catch (Exception e) {
				lError.add("Rainfall in 24h");
			}
			try {
				Double.parseDouble(lInput.get(6));
			} catch (Exception e) {
				lError.add("Air Moisture");
			}
			try {
				Double.parseDouble(lInput.get(7));
			} catch (Exception e) {
				lError.add("Ground Moisture");
			}
			try {
				Double.parseDouble(lInput.get(8));
			} catch (Exception e) {
				lError.add("Air Pressure");
			}
		}
		return lError;
	}

	/*
	 * Ham nay dung de them 1 report vao trong database cung nhu them vao
	 * listReport
	 */
	public void addReport(String text, String listDamaged) {
		weatherSR = new WeatherStationReport(stationID, text, Calendar
				.getInstance().getTime().toString(), listDamaged, "", 0);
		new WeatherStationReportDB().add(weatherSR);
		lReport.add(weatherSR);

	}

	/*
	 * Ham nay tra ve tat ca report hien co, duoc lay tu database
	 */
	public List<WeatherStationReport> getAllReport() {
		List<WeatherStationReport> lWeatherSR = new WeatherStationReportDB()
				.findAll();
		List<WeatherStationReport> lWeatherSRNew = new ArrayList<WeatherStationReport>();
		for (WeatherStationReport wSR : lWeatherSR) {
			if (wSR.getWSID().equals(stationID)) {
				lWeatherSRNew.add(wSR);
			}
		}
		return lWeatherSRNew;
	}

	/*
	 * Ham nay tra ve list gia tri cua nhung cai report
	 */
	public List<String> getAllReportValue() {
		List<String> lReportValue = new ArrayList<String>();
		for (WeatherStationReport wSR : lReport) {
			String report = wSR.getReport() + " " + wSR.getListDamaged() + " "
					+ wSR.getDate() + " "
					+ (wSR.getStatus() == 0 ? "Processing" : "Solved");
			lReportValue.add(report);
		}
		return lReportValue;
	}

	/*
	 * Ham nay dung de lay noi dung cua report
	 */
	public String getValueReport(String selectedValue) {
		List<String> lReportValue = getAllReportValue();
		String[] tmp = selectedValue.split("\\ ");
		return lReportValue.get(Integer.parseInt(tmp[1]) - 1);
	}

	/*
	 * Ham nay dung de lay noi dung cua report response
	 */
	public String getValueReportResponsed(String selectedValue) {
		String[] tmp = selectedValue.split("\\ ");
		String report = lReport.get(Integer.parseInt(tmp[1]) - 1)
				.getReportResponsed();
		return report.equals("") ? "Still not respond..." : report;
	}

	/*
	 * Ham nay dung de cap nhat lai list report khi ma co 1 report reponse den
	 * tu admin
	 */
	public void checkControl() {
		weatherStation = new WeatherStationDB().find(stationID);
		lReport = getAllReport();
	}

	/*
	 * Tra ve co phai quyen admin hay khong
	 */
	public boolean isAdminRole() {
		return weatherStation.getAdminRole() == 1 ? true : false;
	}

	/*
	 * Ham nay dung de them phan hoi tu tram duy tri ung voi report
	 */
	public void addResponsedReport(int selectedIndex, String report) {
		lReport.get(selectedIndex).setReportResponsed(report);
		new WeatherStationReportDB().update(lReport.get(selectedIndex));

	}

	/*
	 * Ham nay dung de set may bi hu hay khong
	 */
	public void isDamaged(int status) {
		weatherStation.setDamaged(status);
		updateDatabaseWeatherStation();

	}

	// thiet lap report la solved hay chua solved
	public void setSolved(int selectedIndex, String selectedValue,
			boolean solved) {
		String[] tmp = selectedValue.split("\\ ");
		if (solved) {
			lReport.get(Integer.parseInt(tmp[1]) - 1).setStatus(1);
		} else {
			lReport.get(Integer.parseInt(tmp[1]) - 1).setStatus(0);
		}
		new WeatherStationReportDB().update(lReport.get(selectedIndex));
	}

	public List<String> getlInput() {
		return lInput;
	}

	public void setlInput(List<String> lInput) {
		this.lInput = lInput;
	}

	public void setAdminRole(boolean adminRole) {
		weatherStation.setAdminRole(adminRole == true ? 1 : 0);
		updateDatabaseWeatherStation();
	}

	public List<WeatherStationReport> getlReport() {
		return lReport;
	}

	public void setlReport(List<WeatherStationReport> lReport) {
		this.lReport = lReport;
	}

	public WeatherStationReport getWeatherSR() {
		return weatherSR;
	}

	public void setWeatherSR(WeatherStationReport weatherSR) {
		this.weatherSR = weatherSR;
	}

	public String getStationID() {
		return stationID;
	}

	public void setStationID(String stationID) {
		this.stationID = stationID;
	}

	public WeatherStation getWeatherStation() {
		return weatherStation;
	}

	public void setWeatherStation(WeatherStation weatherStation) {
		this.weatherStation = weatherStation;
	}

	public WeatherStationCollection getWeatherSC() {
		return weatherSC;
	}

	public void setWeatherSC(WeatherStationCollection weatherSC) {
		this.weatherSC = weatherSC;
	}
}
